// import Vue from 'vue'
import VueRouter from 'vue-router'
// import  from '@/views/login'
// import layout from '@/layout'
// import home from '@/views/home'
// import ask from '@/views/ask'
// import mine from '@/views/mine'
// import video from '@/views/video'
// import store from '@/store'
// import { Toast } from 'vant'
// import edit from '@/views/mine/edit'
// import article from '@/views/home/article'
// import search from '@/views/search'
// import result from '@/views/search/result'
// import chat from '@/views/mine/chat'
import Vue from 'vue'
// const VueRouter = () => import('vue-router')
const login = () => import('@/views/login')
const layout = () => import('@/layout')
const home = () => import('@/views/home')
const ask = () => import('@/views/ask')
const mine = () => import('@/views/mine')
const video = () => import('@/views/video')
const store = () => import('@/store')
import { Toast } from 'vant'
import edit from '@/views/mine/edit'
import article from '@/views/home/article'
import search from '@/views/search'
import result from '@/views/search/result'
import chat from '@/views/mine/chat'
Vue.use(VueRouter)
const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'chat',
    path: '/mine/chat',
    component: chat
  },
  {
    name: 'article',
    path: '/article/:id',
    component: article
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'result',
    path: '/search/result/:key',
    component: result,
    meta: { keepAlive: true }
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    name: 'edit',
    path: '/mine/edit',
    component: edit,
    // meta: { needLoading: true }
    meta: { keepAlive: true }
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      {
        name: 'home',
        path: 'home',
        component: home,
        meta: { keepAlive: true }
      },
      { name: 'ask', path: 'ask', component: ask },
      {
        name: 'mine',
        path: 'mine',
        component: mine,
        // meta: { needLoading: true }
        meta: { keepAlive: true }
      },
      { name: 'video', path: 'video', component: video }
    ]
  }
]

const router = new VueRouter({
  routes,
  mode: 'hash'
})

router.beforeEach((to, from, next) => {
  console.log(to)
  if (to.meta.needLoading) {
    if (store.state.tokenObj.token) {
      next()
    } else {
      Toast.fail('请先登录')
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }
  } else {
    next()
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
